<template>
  <div>
    {{ tip }}
    <div  style="overflow: hidden;">
        <div id="main" style="width: 600px; height: 600px;float: left;position: relative;">
        </div>
        <div id="content" style="float: left;width: 200px;">
            <div v-for="item in msgList">
                {{ item.nickName +"说"+item.msg}}
            </div>
        </div>
    </div>

    <div>
        <div>用户名 <input v-model="username"/></div>
        <input type="text" v-model="msg">
        <button @click="send">发送</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Hls from  "hls.js";
import DPlayer from "dplayer";


let  ws = new WebSocket("ws://192.168.50.107:8080");

let myDplayer = ref();
let tip = ref("首页 直播加弹幕");
let msg = ref();//消息
let username = ref();//用户名
let msgList = ref([]);//消息的集合
let send = ()=>{
    if(username.value){
        ws.send(JSON.stringify({
            nickName:username.value,
            msg:msg.value,
            type:1
        }));
    }else{
        alert("请输入昵称")
    }

}


onMounted(() => {
  const dp = new DPlayer({
    container: document.getElementById("main"),
    live: true,
    video: {
        url: '',
        type: 'customHls',
        customType: {
            customHls: function (video, player) {
                const hls = new Hls();
                hls.loadSource(video.src);
                hls.attachMedia(video);
            },
        },
    },
  });
  myDplayer.value = dp;


  ws.onmessage = function(evt){
   
    let info  = JSON.parse(evt.data);
    
    if(info.type==1){
    console.log(info.nickName+"说"+info.msg);
    msgList.value.push(info);

    let main = document.getElementById("main");//主容器

    let item = document.createElement("item");
  
    Object.assign(item.style,{
        position:"absolute",
        width:"200px",
        textWrap: "nowrap",
        left:main.offsetWidth+"px",
        top:Math.round(Math.random()*200)+"px",
        color:`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255})`     
    })
    item.innerHTML = info.nickName+"说"+info.msg;
    main.appendChild(item);

   let speed = Math.random()*50+10;//
    item.timer = setInterval(()=>{
        item.style.left = item.offsetLeft-speed+"px";
        if(item.offsetLeft<=0){
            clearInterval(item.timer);
            item.remove();
        }
    },200);
  }else if(info.type==2){
        tip.value = info.msg;
  }else if(info.type ==3){
    console.log("开始关闭");
      window.location.href = "http://www.baidu.com"

  }
  

}

});
</script>

<style scoped></style>
